<template>
  <el-dialog
    :title="title"
    :visible="showDialog"
    @close="btnCancel"
  >
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form
      v-if="showDialog"
      ref="addDeptForm"
      label-width="120px"
      :model="formData"
      :rules="rules"
    >
      <el-form-item
        label="部门名称"
        prop="name"
      >
        <el-input
          v-model="formData.name"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item
        label="部门编码"
        prop="code"
      >
        <el-input
          v-model="formData.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item
        label="部门负责人"
        prop="manager"
      >
        <el-select
          v-model="formData.manager"
          style="width: 80%"
          placeholder="请选择"
          @focus="getEmployeeSimple"
          @blur="checkManager"
        >
          <el-option
            v-for="item in employees"
            :key="item.id"
            :lable="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="部门介绍"
        prop="introduce"
      >
        <el-input
          v-model="formData.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row
      slot="footer"
      type="flex"
      justify="center"
    >
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button
          type="primary"
          size="small"
          @click="btnOK"
        >确定</el-button>
        <el-button
          size="small"
          @click="btnCancel"
        >取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getDepartments, addDepartments, getDepartmentDetail, updateDepartments } from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    node: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  data () {
    const checkRepeatName = async (rule, val, callback) => {
      // 1. 获取全部的部门列表
      const { depts } = await getDepartments()
      let isRepeat = false
      // 2. 筛选出当前被点击的部门下属(跟正在创建同级)
      if (this.formData.id) {
        // 编辑
        isRepeat = depts
          .filter(item => item.pid === this.node.pid && item.id !== this.node.id)
          .some(item => item.name === val)
      } else {
        // 新增
        isRepeat = depts
          .filter((item) => item.pid === this.node.id)
          // 3. 判断是否有同名的元素
          .some((item) => item.name === val)
      }

      // 4. 处理后续, 有重名报错, 没有就放行
      isRepeat ? callback(new Error('同一部门下不能重名')) : callback()
    }

    const checkRepeatCode = async (rule, val, callback) => {
      // 1. 获取全部部门
      const { depts } = await getDepartments()
      // 2. 判断是否有相同 code
      // 这里呢也分两种情况, 1. 新增 2. 编辑
      // 如果编辑的情况下 item.id !== this.node.id
      let isRepeat = false
      if (this.formData.id) {
        // 编辑
        isRepeat = depts.some((item) => item.code === val && item.id !== this.node.id)
      } else {
        // 新增
        isRepeat = depts.some((item) => item.code === val)
      }
      // 3. 处理后续
      isRepeat ? callback(new Error('部门编码必须唯一')) : callback()
    }

    return {
      employees: [],
      formData: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '数据不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1-50 之间', trigger: 'blur' },
          { trigger: 'blur', validator: checkRepeatName }
        ],
        code: [
          { required: true, message: '数据不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1-50 之间', trigger: 'blur' },
          { trigger: 'blur', validator: checkRepeatCode }
        ],
        manager: [{ required: true, message: '数据不能为空', trigger: 'blur' }],
        introduce: [
          { required: true, message: '数据不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '长度在 1-300 之间', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title () {
      return this.formData.id ? '编辑部门' : '新增部门'
    }
  },
  methods: {
    async getEmployeeSimple () {
      this.employees = await getEmployeeSimple()
      console.log(this.employees)
    },
    checkManager () {
      setTimeout(() => {
        this.$refs.addDeptForm.validateField('manager')
      }, 100)
    },
    async btnOK () {
      try {
        // 1. 校验表单
        await this.$refs.addDeptForm.validate()
        // 现在不能直接发新增请求了需要判断
        if (this.formData.id) {
          // 编辑
          await updateDepartments(this.formData)
        } else {
          // 新增
          // 2. 发请求 在原表单当中添加 Pid 数据
          await addDepartments({ ...this.formData, pid: this.node.id })
        }
        // 3. 弹出提示
        this.$message.success('添加成功')
        // 4. 关闭弹窗
        // this.showDialog = false
        this.$emit('update:showDialog', false)
        // 5. 提醒父组件更新数据
        this.$emit('addDepts')
      } catch (error) {
        console.log(error)
      }
    },
    btnCancel () {
      // 强制清理所有表单数据, 将 formData 设置为原始值
      this.formData = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
      // 重置表单绑定过的数据, 清理所有的错误提示
      this.$refs.addDeptForm.resetFields()
      // 关闭弹窗
      this.$emit('update:showDialog', false)
    },
    async getDepartmentDetail (id) {
      // 这个地方就是封装我们获取时数据的函数需要一个id
      // 如果是进入组件就应该发请求获取的话, 就直接用 this.node.id
      // 更加灵活的方法调用时才将 id 传入进来
      this.formData = await getDepartmentDetail(id)
    }
  }
}
</script>

<style>
</style>
